package cn.wowjoy.office.applystock.receipts;

import android.app.Instrumentation;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.EngineActionSheet;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.response.ApplyHeadInfoResponse;
import cn.wowjoy.office.data.response.QRVoInfo;
import cn.wowjoy.office.data.response.StockStorageResponse;
import cn.wowjoy.office.databinding.ActivityReceiptsDetailBinding;
import cn.wowjoy.office.utils.ToastUtil;

@Route(path = "/applystock/receipts/receiptsdetail")
public class ReceiptsDetailActivity extends NewBaseActivity<ActivityReceiptsDetailBinding,ReceiptsDetailViewModel> implements View.OnClickListener {


    @Autowired
    int type;
    @Autowired
    boolean isSwipe;
    @Autowired
    String headCode;
    private boolean isHasFlid = false;
    private ApplyHeadInfoResponse applyHeadInfoResponse;
    private LinearLayoutManager linearLayoutManager;

    private EngineActionSheet actionSheet;
    private CommonDialog noticeDialog;
    private boolean isNeedCommit = false;
    private void showNoticeDialog(){
        if (null == noticeDialog)
            noticeDialog = new CommonDialog.Builder()
                    .setTitle("提醒")
                    .setContent("该出库任务还未提交，是否退出？")
                    .setContentGravity(Gravity.CENTER)
                    .setCancelBtn("否", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            noticeDialog.dismissAllowingStateLoss();
                        }
                    })
                    .setConfirmBtn("是", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            noticeDialog.dismissAllowingStateLoss();
                            ReceiptsDetailActivity.this.finish();
                        }
                    })
                    .create();
        noticeDialog.show(getSupportFragmentManager(),"");
    }
    private void showActionSheet(boolean isShow){
        if (null == actionSheet)
            actionSheet = new EngineActionSheet.Builder()
                    .showTitle(isShow)
                    .setTitleSize(16.0f)
                    .setTitleColor(R.color.appTextDialog)
                    .setTitle("确认出库", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                           initCommitData(true);
                            actionSheet.dismiss();
                        }
                    },true)
                    .setBtnSize(16.0f)
                    .setBtnColor(R.color.appText)
                    .setBtn("仅提交", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            initCommitData(false);
                            actionSheet.dismiss();
                        }
                    })
                    .setCancelSize(16.0f)
                    .setCancelColor(R.color.appText)
                    .setCancel("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            actionSheet.dismiss();
                        }
                    })
                    .create();
        actionSheet.show(this);
    }


    private void initCommitData(boolean isConfirm){
        if (isRequisition) {
            applyHeadInfoResponse.setAllocationDetailList(viewModel.adapter.getDatas());
            if (isConfirm)
                applyHeadInfoResponse.setIsConfirm("y");
            else
                applyHeadInfoResponse.setIsConfirm("n");
            viewModel.commit(applyHeadInfoResponse);
        } else {
            applyHeadInfoResponse.setDetailVoInfos(viewModel.adapter.getDatas());
            if (isConfirm)
                applyHeadInfoResponse.setIsConfirm("y");
            else
                applyHeadInfoResponse.setIsConfirm("n");
            viewModel.commit(applyHeadInfoResponse);
        }
    }


    private boolean isRequisition;
    private MDialog waitDialog;
    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }
    }

    @Override
    protected Class<ReceiptsDetailViewModel> getViewModel() {
        return ReceiptsDetailViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_receipts_detail;
    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.content;
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        viewModel.getDetail();
    }


    @Override
    protected void init(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        binding.setViewModel(viewModel);
        viewModel.setHeadCode(headCode);
        viewModel.setType(type);
        initData();
        initView();
        initObsever();
        viewModel.getDetail();

    }


    private void initData(){
        switch (type){
            case Constants.RECEIPTS_CODE_APPLY:
                isRequisition = false;
                binding.toolbarTitle.setText("申领单详情");
                break;
            case Constants.RECEIPTS_CODE_APPLY_FOR:
                isRequisition = false;
                binding.toolbarTitle.setText("申请单详情");
                break;
            case Constants.RECEIPTS_CODE_ALLOT:
                isRequisition = true;
                binding.toolbarTitle.setText("调拨单详情");

                break;
        }
        binding.setIsRequisition(isRequisition);
        binding.setIsSwipe(isSwipe);

    }

    private void initView(){
        setScrollAfterAdd(true);
        binding.back.setOnClickListener(this);
        binding.commit.setOnClickListener(this);
        viewModel.adapter.setRequisition(isRequisition);
        viewModel.adapter.setSwipe(isSwipe);
        linearLayoutManager = new LinearLayoutManager(this);
        binding.recyclerView.setLayoutManager(linearLayoutManager);
        binding.recyclerView.setAdapter(viewModel.lAdapter);
        binding.recyclerView.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
        binding.recyclerView.setEmptyView(binding.emptyView.getRoot());
        binding.recyclerView.setPullRefreshEnabled(false);
        binding.appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset < 0){
                    isHasFlid = true;
                } else {
                    isHasFlid = false;
                }
            }
        });
        binding.recyclerView.addOnScrollListener(mOnScrollListener);

    }


    /**
     * 模拟滑动事件
     */
    private void mockFliding(){
        if (!isHasFlid)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Instrumentation inst = new Instrumentation();
                    float x = 45.0f;
                    float y = binding.appbar.getHeight();
                    long dowTime = SystemClock.uptimeMillis();
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime,
                            MotionEvent.ACTION_DOWN, x, y,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime,
                            MotionEvent.ACTION_MOVE, x, y - 50,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+20,
                            MotionEvent.ACTION_MOVE, x, y - 100,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+30,
                            MotionEvent.ACTION_MOVE, x, y - 150,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+40,
                            MotionEvent.ACTION_MOVE, x, y - 200,0));
                    inst.sendPointerSync(MotionEvent.obtain(dowTime,dowTime+40,
                            MotionEvent.ACTION_UP, x, y - 250,0));
//                    ifFcousFliding = true;
                }
            }).start();

    }
    private boolean move = false;
    private int mToPosition;
    private void smoothMoveToPosition(int n) {
        int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = linearLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            binding.recyclerView.smoothScrollToPosition(n++);
        } else if (n <= lastItem) {
            int movePosition = n - firstItem;
            if (movePosition >= 0 && movePosition < binding.recyclerView.getChildCount()) {
                int top = binding.recyclerView.getChildAt(movePosition).getTop()+binding.appbar.getHeight();
                binding.recyclerView.smoothScrollBy(0, top);
            }
//            int top = binding.recyclerView.getChildAt(n - firstItem).getTop();
//            binding.recyclerView.smoothScrollBy(0, top);
        } else {
            mToPosition = n;
            binding.recyclerView.smoothScrollToPosition(n++);
            move = true;
        }

//        binding.recyclerView.smoothScrollToPosition(n);
////            smoothMoveToPosition(mIndex);
//        move = true;

    }
    private boolean scrollAfterAdd = false;
    public boolean isScrollAfterAdd() {
        return scrollAfterAdd;
    }

    public void setScrollAfterAdd(boolean scrollAfterAdd) {
        this.scrollAfterAdd = scrollAfterAdd;
    }
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (move ) {
                move = false;
                //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                int n = position - linearLayoutManager.findFirstVisibleItemPosition();
                if (0 <= n && n < binding.recyclerView.getChildCount()) {
                    //获取要置顶的项顶部离RecyclerView顶部的距离
                    int top = binding.recyclerView.getChildAt(n % 5).getTop()+binding.appbar.getHeight();
                    //最后的移动
                    binding.recyclerView.scrollBy(0, top);
                }
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);

//
//            if (newState == RecyclerView.SCROLL_STATE_DRAGGING && isScrollAfterAdd()) {
//                setScrollAfterAdd(false);
//
//            }
//
//            if (move && newState == RecyclerView.SCROLL_STATE_IDLE) {
//                move = false;
//                    int n = position - linearLayoutManager.findFirstVisibleItemPosition();
//                    if (0 <= n && n < binding.recyclerView.getChildCount()) ;
//                    int top = binding.recyclerView.getChildAt(n % 5).getTop()+binding.appbar.getHeight();
//                    binding.recyclerView.smoothScrollBy(0, top);
//
//            }
            if (move) {
                move = false;
                smoothMoveToPosition( mToPosition);
            }

        }
    };

    private int position = -1;

    private void initObsever(){
        viewModel.response.observe(this, new Observer<LiveDataWrapper<ApplyHeadInfoResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<ApplyHeadInfoResponse> applyHeadInfoResponseLiveDataWrapper) {
                switch (applyHeadInfoResponseLiveDataWrapper.status){
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(ReceiptsDetailActivity.this);
                        break;
                    case SUCCESS:
                        clearDialog();
                        applyHeadInfoResponse = applyHeadInfoResponseLiveDataWrapper.data;
                        binding.setModel(applyHeadInfoResponseLiveDataWrapper.data);
                        break;
                    case ERROR:
                        clearDialog();
                        handleException(applyHeadInfoResponseLiveDataWrapper.error,true);

                        break;
                }
            }
        });
        viewModel.permission.observe(this, new Observer<LiveDataWrapper<StockStorageResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<StockStorageResponse> stringLiveDataWrapper) {
                switch (stringLiveDataWrapper.status){
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(ReceiptsDetailActivity.this);
                        break;
                    case SUCCESS:
                        if (TextUtils.equals("y",stringLiveDataWrapper.data.getPermission())){
                            showActionSheet(true);
                        } else {
                            showActionSheet(false);
                        }
                        clearDialog();

                        break;
                    case ERROR:
                        clearDialog();
                        handleException(stringLiveDataWrapper.error,false);

                        break;
                }
            }
        });
        viewModel.create.observe(this, new Observer<LiveDataWrapper<Object>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<Object> stringLiveDataWrapper) {
                switch (stringLiveDataWrapper.status){
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(ReceiptsDetailActivity.this);
                        break;
                    case SUCCESS:
                        clearDialog();
                        isNeedCommit = false;
                        binding.toolbar.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent();
                                intent.putExtra(Constants.IS_NEED_REFRESH, true);
                                setResult(RESULT_OK,intent);
                                ReceiptsDetailActivity.this.finish();
                            }
                        },500);
                        break;
                    case ERROR:
                        clearDialog();
                        handleException(stringLiveDataWrapper.error,false);

                        break;
                }
            }
        });
        viewModel.scanData.observe(this, new Observer<LiveDataWrapper<QRVoInfo>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<QRVoInfo> qrVoInfoLiveDataWrapper) {
                switch (qrVoInfoLiveDataWrapper.status){
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(ReceiptsDetailActivity.this);
                        break;
                    case SUCCESS:
                        clearDialog();
                        position = viewModel.adapter.addQRVoInfo(qrVoInfoLiveDataWrapper.data,isRequisition);
                        if (position >= 0){
                            binding.recyclerView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    smoothMoveToPosition(position);
                                    position = -1;
                                }
                            },500);

                            isNeedCommit = true;
                        }

                        break;
                    case ERROR:
                        clearDialog();
                        handleException(qrVoInfoLiveDataWrapper.error,false);

                        break;

                }
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.back:
                onBackPressed();
                break;
            case R.id.commit:
                //提交：先请求权限，再提交
                viewModel.isExamineAndConfirmOut();
                break;

        }
    }

    @Override
    public void onBackPressed() {

        if (isNeedCommit){
            showNoticeDialog();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        openBroadCast();
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeBroadCast();
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        Log.d("QRCODE",msg);
        mockFliding();
        setScrollAfterAdd(true);
        if (msg.contains("code")/* && msg.contains("物资编码")*/) {

//            String replace = msg.replace("二维码编码", "qrCode")/*.replace("物资编码", "goodsCode")*/;
//            Log.e("SS", "brodcast: " + replace);

            String qrCode = msg.substring(msg.indexOf(":") + 1, msg.length());
            Log.e("PXY", "code: "+ qrCode);
            viewModel.queryByScan(qrCode);

        } else {
            ToastUtil.toastWarning(ReceiptsDetailActivity.this, "该物资不属于出库范围", -1);
        }
    }
}
